import getExt from "./getExt";
export default async function getBtoaWithCanvas(url, crossOrigin = false) {
  try {
    const imgElement = await new Promise((resolve, reject) => {
      const image = new Image();
      if (crossOrigin) {
        image.setAttribute("crossOrigin", "anonymous");
      }
      image.src = url;
      image.onload = () => {
        resolve(image);
      };
      image.onerror = () => {
        reject("Image loading failed");
      };
    });
    return await new Promise((resolve) => {
      const canvas = document.createElement("canvas");
      const { width, height, src } = imgElement;
      canvas.width = width;
      canvas.height = height;
      const ctx = canvas.getContext("2d");
      ctx.drawImage(imgElement, 0, 0, width, height);
      const ext = getExt(src) || "png";
      const dataURL = canvas.toDataURL(`image/${ext}`, 1);
      ctx.clearRect(0, 0, width, height);
      resolve(dataURL);
    });
  } catch (error) {
    const typeError = new TypeError();
    typeError.data = {
      code: 0,
      message: "Failed",
      data: {
        error,
      },
    };
    return Promise.reject(typeError);
  }
}

// getBtoaWithCanvas(
//   "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3636058960,1338604857&fm=26&gp=0.jpg",
//   true
// )
//   .then((ret) => {
//     console.log(ret);
//   })
//   .catch((err) => {
//     console.log(err.data);
//   });
